<template>
	<view class="edit-profile-page">
		<!-- 昵称编辑 -->
		<uni-popup ref="nicknamePopup" type="dialog">
			<uni-popup-dialog mode="input" title="编辑昵称" :value="tempProfile.name" placeholder="请输入昵称"
				@confirm="confirmNickname"></uni-popup-dialog>
		</uni-popup>
		<!-- 简介编辑 -->
		<uni-popup ref="bioPopup" type="dialog">
			<uni-popup-dialog mode="input" inputType="textarea" title="编辑简介" :value="tempProfile.description" placeholder="请输入简介"
				@confirm="confirmBio"></uni-popup-dialog>
		</uni-popup>

		<view class="profile-group">
			<view class="profile-item" @click="openEditPopup('name')">
				<text class="item-label">昵称</text>
				<view class="item-content">
					<text class="item-value">{{ profile.name }}</text>
					<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
				</view>
			</view> 
			<view class="profile-item" @click="chooseAvatar">
				<text class="item-label">头像</text>
				<view class="item-content">
					<image class="avatar-img" :src="profile.photo" mode="aspectFill" @error="avatarLoadError"></image>
					<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
				</view>
			</view>
			<view class="profile-item" @click="openEditPopup('description')">
				<text class="item-label">简介</text>
				<view class="item-content">
					<text class="item-value ellipsis">{{ profile.description }}</text>
					<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
				</view>
			</view>
		</view>

		<view class="profile-group">
			<picker mode="selector" :range="genderRange" :value="genderIndex" @change="bindGenderChange">
				<view class="profile-item">
					<text class="item-label">性别</text>
					<view class="item-content">
						<text class="item-value" :class="{'link-style': !profile.gender}">
							{{ profile.gender || '去选择' }}
						</text>
						<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
					</view>
				</view>
			</picker>
			<!--<picker mode="date" :value="profile.birthday" :start="birthdayStartDate" :end="birthdayEndDate" @change="bindBirthdayChange">
				<view class="profile-item">
					<text class="item-label">生日</text>
					<view class="item-content">
						<text class="item-value" :class="{'link-style': !profile.birthday}">
							{{ profile.birthday || '去选择' }}
						</text>
						<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
					</view>
				</view>
			</picker>-->
		</view>

		<view class="profile-group">
			<view class="profile-item">
				<text class="item-label">芝麻信用</text>
				<view class="item-content">
					<text class="item-value-static">{{ profile.sesameCredit || '信用良好' }}</text>
				</view>
			</view>
			<picker mode="region" @change="bindLocationChange" :value="locationArray">
				<view class="profile-item">
					<text class="item-label">常住地</text>
					<view class="item-content">
						<text class="item-value" :class="{'link-style': !profile.location}">
							{{ profile.location || '去选择' }}
						</text>
						<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
					</view>
				</view>
			</picker>
			<!-- 语音签名，需要调用录音接口 -->
			<!--<view class="profile-item" @click="editItem('voiceSignature')">
				<text class="item-label">语音签名</text>
				<view class="item-content">
					<text class="item-value link-style">{{ profile.voiceSignature || '去录制' }}</text>
					<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
				</view>
			</view>-->
		</view>
		
		<!--<view class="group-footer-title">鱼小铺信息</view>
		<view class="profile-group">
			<view class="profile-item" @click="editItem('domain')">
				<text class="item-label">领域</text>
				<view class="item-content">
					<text class="item-value">{{ profile.domain || '技能服务' }}</text>
					<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
				</view>
			</view>
		</view>-->

		<view class="save-button-container">
			<button class="save-btn" @click="saveProfile" :loading="isSaving">保存</button>
		</view>
		<view :style="{height: '40rpx'}"></view> <!-- 底部留白 -->
	</view>
</template>

<script>
// 假设你的环境变量配置文件路径，请根据实际情况修改
import ENV_CONFIG from '@/config/env.js'; // 如果有统一的环境配置
const app = getApp()
export default {
	data() {
		return {
			profile: {
				name: '',
				photo: '',
				description: '',
				gender: '', // '男', '女', '保密'
				birthday: '', // 'YYYY-MM-DD'
				hobbies: '',
				school: '',
				sesameCredit: '',
				location: '', // '省 市 区'
			},
			tempProfile: { // 用于弹窗编辑的临时数据
				name: '',
				description: ''
			},
			genderRange: ['男', '女', '保密'],
			isSaving: false,
			// locationArray: [], // 用于 picker mode="region" 的显示 ['省', '市', '区']
		};
	},
	computed: {
		genderIndex() {
			return this.genderRange.indexOf(this.profile.gender);
		},
		birthdayStartDate() {
			const currentYear = new Date().getFullYear();
			return `${currentYear - 100}-01-01`;
		},
		birthdayEndDate() {
			const today = new Date();
			const year = today.getFullYear();
			const month = (today.getMonth() + 1).toString().padStart(2, '0');
			const day = today.getDate().toString().padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		locationArray() {
			if (this.profile.location) {
				return this.profile.location.split(' ');
			}
			return [];
		}
	},
	onLoad() {
		uni.setNavigationBarTitle({
			title: '编辑资料'
		});
		let userInfo = uni.getStorageSync('userInfo')
		if(userInfo){
			// this.profile = userInfo
			this.profile.description = userInfo.description
			this.profile.location = userInfo.location
			this.profile.name = userInfo.name
			this.profile.photo = userInfo.photo
			this.profile.gender = userInfo.gender
		}
		// 实际项目中，这里应该从API获取用户当前信息
		// this.fetchUserProfile();
	},
	methods: {
		// fetchUserProfile() { /* API获取用户信息逻辑 */ },

		avatarLoadError() {
			console.log('头像加载失败，使用默认头像');
			if (this.profile.photo !== DEFAULT_AVATAR) {
				this.profile.photo = DEFAULT_AVATAR;
			}
		},
		openEditPopup(type) {
			if (type === 'name') {
				this.tempProfile.name = this.profile.name;
				this.$refs.nicknamePopup.open();
			} else if (type === 'description') {
				this.tempProfile.description = this.profile.description;
				this.$refs.bioPopup.open();
			}
		},
		confirmNickname(value) {
			this.profile.name = value;
		},
		confirmBio(value) {
			this.profile.description = value;
		},

		chooseAvatar() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					this.uploadAvatar(tempFilePath);
				},
				fail: (err) => {
					console.log('选择图片失败', err);
					if (err.errMsg !== "chooseImage:fail cancel") { // 用户取消选择时不提示
						uni.showToast({ title: '选择图片失败', icon: 'none' });
					}
				}
			});
		},
		async uploadAvatar(filePath) {
			uni.showLoading({ title: '上传中...' });
			try {
				const uploadResult = await uni.uploadFile({
					url: ENV_CONFIG['wx_dev'].requestBaseUrl + app.globalData.ApiConstant.Oss.upload,
					filePath: filePath,
					name: 'file', // 与后端约定的文件字段名
					header: {
						'token': uni.getStorageSync('token') || '' // 从storage获取token
					},
					// formData: { // 其他需要附带的参数
					// 	userId: this.userId 
					// }
				});

				if (uploadResult[0]) { // uni.uploadFile 返回的是数组 [err, res]
					uni.hideLoading();
					console.error('上传失败(uni.uploadFile err):', uploadResult[0]);
					uni.showToast({ title: '头像上传失败', icon: 'none' });
					return;
				}
				
				const res = JSON.parse(uploadResult.data); // uploadResult[1] 是服务器的响应
				console.log('Upload API Response:', res);

				if (res.code === 0 && res.msg === 'success') {
					if (res.code === 0 && res.url) { // 假设后端返回 {code: 0, msg: 'success', url: '...'}
						this.profile.photo = res.url;
						uni.hideLoading();
						uni.showToast({ title: '头像上传成功', icon: 'success' });
					} else {
						uni.hideLoading();
						uni.showToast({ title: res.msg || '头像上传失败', icon: 'none' });
					}
				} else {
					uni.hideLoading();
					uni.showToast({ title: `上传错误: ${res.msg}`, icon: 'none' });
				}
			} catch (error) {
				uni.hideLoading();
				console.error('上传头像异常:', error);
				uni.showToast({ title: '头像上传异常', icon: 'none' });
			}
		},
		bindGenderChange(e) {
			this.profile.gender = this.genderRange[e.detail.value];
		},
		bindBirthdayChange(e) {
			this.profile.birthday = e.detail.value;
		},
		bindLocationChange(e) {
			this.profile.location = e.detail.value.join(' '); // value 是一个数组 ['省', '市', '区']
		},
		editItem(itemKey) {
			// 对于一些复杂的编辑，可能需要跳转到新页面或使用更复杂的弹窗组件
			uni.showToast({
				title: `编辑 ${itemKey} 功能待完善`,
				icon: 'none'
			});
		},
		async saveProfile() {
			if (this.isSaving) return;
			this.isSaving = true;
			uni.showLoading({ title: '保存中...' });

			// 准备要发送到后端的数据
			const dataToSave = { ...this.profile };
			// 可以在这里做一些数据校验
			if (!dataToSave.name.trim()) {
				uni.hideLoading();
				this.isSaving = false;
				uni.showToast({ title: '昵称不能为空', icon: 'none' });
				return;
			}
			
			console.log("准备保存的数据:", dataToSave);

			try {
				
				app.globalData.Request.post(app.globalData.ApiConstant.User.editProfile, 
					{
						...this.profile
					}
				).then((res)=>{
					this.isSaving = false;
					console.log('Save API Response:', res);
					if (res.code === 0 && res.data && res.msg === 'success') { // 假设后端成功返回 {code: 0, msg: 'success'}
						uni.showToast({ title: '保存成功', icon: 'success' });
						// 可选：保存成功后返回上一页
						setTimeout(() => {
							wx.reLaunch({
								url: '/pages/tb/home/home',
							})
						}, 1500);
					} else {
						uni.showToast({ title: (res.data && res.msg) || `保存失败`, icon: 'none' });
					}
				}).catch((err)=>{
					uni.hideLoading();
					this.isSaving = false;
					console.error('保存信息异常:', error);
					uni.showToast({ title: '保存异常', icon: 'none' });
				}).finally((res)=>{
					uni.hideLoading();
				})

				
				

			} catch (error) {
				uni.hideLoading();
				this.isSaving = false;
				console.error('保存信息异常:', error);
				uni.showToast({ title: '保存异常', icon: 'none' });
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.edit-profile-page {
	background-color: #f7f8fa;
	min-height: 100vh;
	padding-top: 1rpx;
	padding-bottom: 140rpx; /* 为保存按钮留出空间 */
}

.profile-group {
	margin: 24rpx;
	background-color: #ffffff;
	border-radius: 16rpx;
	overflow: hidden;

	.profile-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		position: relative;
		min-height: 50rpx; // 确保picker等能正常触发

		&:not(:last-child)::after {
			content: '';
			position: absolute;
			left: 30rpx;
			right: 0;
			bottom: 0;
			height: 1px;
			background-color: #f5f5f5;
			transform: scaleY(0.5);
		}

		.item-label {
			font-size: 30rpx;
			color: #303133;
			flex-shrink: 0;
			margin-right: 20rpx;
		}

		.item-content {
			display: flex;
			align-items: center;
			flex-grow: 1;
			justify-content: flex-end;
			overflow: hidden;

			.item-value {
				font-size: 28rpx;
				color: #606266;
				text-align: right;
				&.placeholder {
					color: #C0C4CC;
				}
				&.ellipsis {
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					max-width: 400rpx;
				}
			}
			.item-value-static {
				font-size: 28rpx;
				color: #606266;
			}
			.link-style {
				color: #409eff;
			}

			.avatar-img {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 10rpx;
				background-color: #f0f0f0; // 图片加载前占位背景
			}
			uni-icons {
				margin-left: 10rpx;
				color: #C0C4CC; // 统一箭头颜色
			}
		}
	}
}
.group-footer-title {
	padding: 20rpx 30rpx 0;
	font-size: 28rpx;
	color: #909399;
}

.save-button-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	background-color: #f7f8fa; // 与页面背景色一致或#fff
	padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	z-index: 100;
	.save-btn {
		background-color: #ffc800; // 闲鱼黄
		color: #303133;
		font-size: 32rpx;
		border-radius: 40rpx;
		height: 88rpx;
		line-height: 88rpx;
		&:after {
			border: none;
		}
		&[loading] {
			background-color: #ffe573; // loading时颜色变浅
		}
	}
}
</style>